package com.wenx.v3system.modular.platform.controller;

import com.wenx.base.rest.BaseRestController;
import com.wenx.v3core.response.R;
import com.wenx.v3secure.annotation.RequiresPermissions;
import com.wenx.v3system.modular.platform.domain.dto.LoginRequest;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserDto;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserRequest;
import com.wenx.v3system.modular.platform.domain.query.PlatformUserQuery;
import com.wenx.v3secure.enums.PlatformPermission;
import com.wenx.v3system.modular.platform.service.PlatformUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

import static com.wenx.v3secure.annotation.RequiresPermissions.Logical.OR;

/**
 * 平台用户管理控制器
 * 
 * @author wenx
 */
@Tag(name = "平台用户管理API")
@RestController
@RequestMapping("/api/v3/platform/users")
public class PlatformUserRestController extends BaseRestController<PlatformUserDto, PlatformUserQuery, PlatformUserService> {


    public PlatformUserRestController(PlatformUserService service) {
        super(service);
    }

    @Override
    @Operation(summary = "分页查询平台用户", description = "根据查询条件分页获取平台用户列表")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    @PostMapping("/page")
    public R page(@RequestBody PlatformUserQuery query) {
        return R.ok(service.page(query));
    }

    @Override
    @Operation(summary = "根据ID获取平台用户", description = "通过用户ID获取平台用户详细信息")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    @GetMapping("/get/{id}")
    public R get(@PathVariable Serializable id) {
        return R.ok(service.get(id));
    }

    @Override
    @Operation(summary = "删除平台用户", description = "根据用户ID删除平台用户")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Serializable id) {
        service.delete(Long.valueOf(id.toString()));
        return R.ok();
    }

    @Override
    @Operation(summary = "更新平台用户", description = "更新平台用户信息")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    @PutMapping("/update")
    public R update(@RequestBody PlatformUserDto dto) {
        service.update(dto);
        return R.ok();
    }

    @Override
    @Operation(summary = "添加平台用户", description = "创建新的平台用户")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    @PostMapping("/add")
    public R add(@RequestBody PlatformUserDto dto) {
        service.add(dto);
        return R.ok();
    }

    @GetMapping("/username/{username}")
    @Operation(summary = "根据用户名查询用户")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    public R getUserByUsername(@PathVariable String username) {
        PlatformUserDto user = service.getUserByUsername(username);
        return R.ok(user);
    }

    @GetMapping("/{userId}/roles")
    @Operation(summary = "获取用户角色")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    public R getUserRoles(@PathVariable Long userId) {
        List<String> roles = service.getUserRoles(userId);
        return R.ok(roles);
    }

    @GetMapping("/{userId}/accessible-tenants")
    @Operation(summary = "获取用户可访问的租户")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.TENANT_READ_CODE}, logical = OR)
    public R getUserAccessibleTenants(@PathVariable Long userId) {
        List<String> tenants = service.getUserAccessibleTenants(userId);
        return R.ok(tenants);
    }

    @PostMapping("/{userId}/assign-roles")
    @Operation(summary = "分配用户角色")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    public R assignUserRoles(
            @PathVariable Long userId,
            @RequestBody List<String> roleIds) {
        service.assignUserRoles(userId, roleIds);
        return R.ok("角色分配成功");
    }

    @PostMapping("/{userId}/tenant-access")
    @Operation(summary = "设置用户租户访问权限")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.TENANT_ALL_CODE}, logical = OR)
    public R setUserTenantAccess(
            @PathVariable Long userId,
            @RequestBody PlatformUserRequest request) {
        service.setUserTenantAccess(userId, request.getAccessType(), request.getTenantIds());
        return R.ok("租户访问权限设置成功");
    }

    @PostMapping("/{userId}/reset-password")
    @Operation(summary = "重置用户密码")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    public R resetUserPassword(@PathVariable  Long userId) {
        String newPassword = service.resetUserPassword(userId);
        return R.ok("密码重置成功", newPassword);
    }

    @PostMapping("/{userId}/toggle-status")
    @Operation(summary = "切换用户状态")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    public R toggleUserStatus(
            @PathVariable Long userId,
            @RequestBody PlatformUserRequest request) {
        service.updateUserStatus(userId, request.getStatus());
        return R.ok("用户状态切换成功");
    }

    @PostMapping("/check-username")
    @Operation(summary = "检查用户名是否存在")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    public R checkUsernameExists(@RequestBody PlatformUserRequest request) {
        boolean exists = service.checkUsernameExists(request.getUsername(), request.getExcludeUserId());
        return R.ok(exists);
    }

    @PostMapping("/check-email")
    @Operation(summary = "检查邮箱是否存在")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    public R checkEmailExists(@RequestBody PlatformUserRequest request) {
        boolean exists = service.checkEmailExists(request.getEmail(), request.getExcludeUserId());
        return R.ok(exists);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public R login(@RequestBody LoginRequest request) {
        PlatformUserDto user = service.login(request.getUsername(), request.getPassword());
        if (user == null) {
            return R.failed("用户名或密码错误");
        }
        return R.ok("登录成功", user);
    }

    @PostMapping("/{userId}/update-login-info")
    @Operation(summary = "更新最后登录信息")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_ALL_CODE}, logical = OR)
    public R updateLastLoginInfo(
            @PathVariable Long userId,
            @RequestBody PlatformUserRequest request) {
        service.updateLastLoginInfo(userId, request.getLoginIp());
        return R.ok("登录信息更新成功");
    }

    @GetMapping("/{userId}/permissions")
    @Operation(summary = "获取用户所有权限")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    public R getUserAllPermissions(@PathVariable Long userId) {
        List<String> permissions = service.getUserPermissions(userId);
        return R.ok(permissions);
    }

    @PostMapping("/{userId}/check-permission")
    @Operation(summary = "检查用户权限")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.PLATFORM_USER_READ_CODE}, logical = OR)
    public R hasPermission(
            @PathVariable Long userId,
            @RequestBody PlatformUserRequest request) {
        boolean hasPermission = service.hasPermission(userId, request.getPermission());
        return R.ok(hasPermission);
    }

    @PostMapping("/{userId}/check-tenant-access")
    @Operation(summary = "检查用户是否可访问租户")
    @RequiresPermissions(value = {PlatformPermission.PLATFORM_ALL_CODE, PlatformPermission.TENANT_READ_CODE}, logical = OR)
    public R canAccessTenant(
            @PathVariable Long userId,
            @RequestBody PlatformUserRequest request) {
        boolean canAccess = service.canAccessTenant(userId, request.getTenantId());
        return R.ok(canAccess);
    }
}